#!/bin/bash

# -----------------------------------------------------------------------------
# Kubernetes Pod 监控部署清单生成脚本
# -----------------------------------------------------------------------------

echo "--- Kubernetes Pod 监控部署清单生成器 ---"

# 1. 交互式输入项目名称
read -p "请输入项目名称 (例如: 衡美生产): " PROJECT_NAME_INPUT

# 2. 交互式输入告警接收邮箱列表
read -p "请输入告警接收邮箱 (多个邮箱请用逗号分隔): " RECEIVER_EMAIL_INPUT

# 3. 交互式输入发件邮箱的授权码 (敏感信息，请勿使用登录密码)
# 使用 -s 选项隐藏输入
read -s -p "请输入发件邮箱的授权码 (输入时不会显示): " SENDER_AUTH_CODE_INPUT
echo "" # 换行

# 确保输入不为空
if [ -z "$PROJECT_NAME_INPUT" ] || [ -z "$RECEIVER_EMAIL_INPUT" ] || [ -z "$SENDER_AUTH_CODE_INPUT" ]; then
    echo "错误：所有字段都必须填写。脚本已退出。"
    exit 1
fi

echo ""
echo "正在生成 Kubernetes YAML 配置..."
echo "---------------------------------------------------"

# 定义临时文件名
MANIFEST_FILE="pod-monitor-manifest-temp-$(date +%s).yaml"

# 使用 Here Document 方式输出最终的 YAML 配置到临时文件
cat <<EOF > "$MANIFEST_FILE"
# Kubernetes Pod 监控部署清单 (自动生成)

# Namespace
apiVersion: v1
kind: Namespace
metadata:
  name: pod-monitor
---
# 1. RBAC 权限设置 (重要！脚本需要读取所有 Pod 的状态)
apiVersion: v1
kind: ServiceAccount
metadata:
  name: pod-monitor-sa
  namespace: pod-monitor
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pod-monitor-role
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: pod-monitor-binding
subjects:
- kind: ServiceAccount
  name: pod-monitor-sa
  namespace: pod-monitor
roleRef:
  kind: ClusterRole
  name: pod-monitor-role
  apiGroup: rbac.authorization.k8s.io

---
# 2. ConfigMap: 普通配置
apiVersion: v1
kind: ConfigMap
metadata:
  name: monitor-config
  namespace: pod-monitor
data:
  PROJECT_NAME: "$PROJECT_NAME_INPUT"
  SMTP_SERVER: "smtp.88.com"
  SMTP_PORT: "465"
  SENDER_EMAIL: "digiwin.alarm@88.com"
  RECEIVER_EMAIL: "$RECEIVER_EMAIL_INPUT"
  CONFIRM_DELAY: "300"    # 持续异常多少秒（秒）才告警
  SILENCE_PERIOD: "3600" # 告警静默期（秒）
  SCAN_INTERVAL: "10"    # 扫描频率（秒）

---
# 3. Secret: 敏感配置 (邮箱授权码)
# 注意：SENDER_AUTH_CODE 是授权码，而不是登录密码。
apiVersion: v1
kind: Secret
metadata:
  name: monitor-secret
  namespace: pod-monitor
type: Opaque
stringData:
  SENDER_AUTH_CODE: "$SENDER_AUTH_CODE_INPUT"

---
# 4. Deployment: 部署应用
apiVersion: apps/v1
kind: Deployment
metadata:
  name: k8s-pod-monitor
  namespace: pod-monitor
  labels:
    app: pod-monitor
spec:
  replicas: 1
  selector:
    matchLabels:
      app: pod-monitor
  template:
    metadata:
      labels:
        app: pod-monitor
    spec:
      serviceAccountName: pod-monitor-sa # 绑定权限
      containers:
      - name: monitor
        # 替换成你构建的镜像地址
        image: registry.digiwincloud.com.cn/bitnami/my-k8s-monitor:v4
        imagePullPolicy: IfNotPresent
        envFrom:
        - configMapRef:
            name: monitor-config
        env:
        - name: SENDER_AUTH_CODE
          valueFrom:
            secretKeyRef:
              name: monitor-secret
              key: SENDER_AUTH_CODE
        resources:
          limits:
            cpu: 200m
            memory: 256Mi
          requests:
            cpu: 50m
            memory: 64Mi

EOF

echo "---------------------------------------------------"

# 检查 YAML 文件是否成功生成
if [ -f "$MANIFEST_FILE" ]; then
    echo "YAML 配置已保存到临时文件：$MANIFEST_FILE。"
    echo "正在尝试自动部署 (kubectl apply)..."
    
    # 执行部署命令
    kubectl apply -f "$MANIFEST_FILE"
    
    # 检查 kubectl 命令的退出状态
    if [ $? -eq 0 ]; then
        echo ""
        echo "✅ 部署成功！所有资源 (Namespace, RBAC, ConfigMap, Secret, Deployment) 已创建/更新。"
    else
        echo ""
        echo "❌ 自动部署失败。请检查您的 kubectl 配置和集群连接。"
    fi
    
    # 清理临时文件
    rm "$MANIFEST_FILE"
    echo "临时文件 $MANIFEST_FILE 已清理。"

else
    echo "❌ YAML 配置生成失败，无法执行部署。"
fi

# 退出脚本
exit 0
